package org.example.studyonline.Realm;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.example.studyonline.mapper.UserMapper;
import org.example.studyonline.mapper.UserRoleMapper;
import org.example.studyonline.pojo.User;
import org.example.studyonline.pojo.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    /**认证**/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String email = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        // 查询用户信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email", email);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UnknownAccountException("账户不存在!");
        }
        if (!password.equals(user.getPassword())) {
            throw new UnknownAccountException("密码错误!");
        }
        return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), password, getName());

    }

    /**授权**/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        SimpleAuthorizationInfo authrizationInfo = new SimpleAuthorizationInfo();

        String email = (String) principals.getPrimaryPrincipal();
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("email", email);
        User user = userMapper.selectOne(queryWrapper1);

        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", user.getUserID());
        List<UserRole> roles = userRoleMapper.selectList(queryWrapper);
        for(UserRole role : roles){
            authrizationInfo.addRole(String.valueOf(role.getRoleID()));
        }
        return authrizationInfo;
    }


}